package org.adream.account.service.scfire;

import javax.annotation.Resource;

import org.adream.account.util.HttpClientUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

@Component
@EnableAsync
public class SynScFireService {
	
	private static Long expiration;	//过期时间
	
	private static String token;
	
	@Value("${scFire.grant.type}")
	private String grantType;
	
	@Value("${scFire.client.id}")
	private String clientId;
	
	@Value("${scFire.client.secret}")
	private String clientSecret;
	
	@Value("${scFire.getTokenUrl}")
	private String getTokenUrl;
	
	@Value("${scFire.userUpdateUrl}")
	private String userUpdateUrl;
	
	@Resource
	private TaskExecutor taskExecutor;
	
	private final static Logger logger = LoggerFactory.getLogger(SynScFireService.class);
	
	/**
	 * 同步火堆用户数据
	 * @param scFireUser
	 */
	@Async
	public void synScFireUser(SynScFireUserEntity scFireUser) {
		long now = System.currentTimeMillis();
		//过期时间不存在(即未调用过getToken()方法) || token不存在 || token已过期
		if(expiration == null || StringUtils.isEmpty(token) || expiration < now) {
			token = getToken();
			if(StringUtils.isEmpty(token)) {
				logger.warn("获取token失败:(");
				return;
			}
		}
		scFireUser.setUchannel("cas");
		scFireUser.setAccess_token(token);
		taskExecutor.execute(new Runnable() {
			@Override
			public void run() {
				HttpClientUtil.httpObjectPost(userUpdateUrl, scFireUser);
			}
		});
	}
	
	/**
	 * 获取token
	 * @return
	 */
	private String getToken() {
		SynScFireLoginEntity scFireLogin = new SynScFireLoginEntity();
		scFireLogin.setGrant_type(grantType);
		scFireLogin.setClient_id(clientId);
		scFireLogin.setClient_secret(clientSecret);
		String tokenInfoString = HttpClientUtil.httpObjectPost(getTokenUrl, scFireLogin);
		if(StringUtils.isEmpty(tokenInfoString)) {
			logger.warn("获取token失败:(");
			token = null;
			expiration = null;
		} else {
			JSONObject tokenInfo = JSON.parseObject(tokenInfoString);
			//设置token值和token过期时间
			token = tokenInfo.getString("value");
			expiration = tokenInfo.getLong("expiration");
		}
		return token;
	}
}